package com.briup.cms.web.interceptor;

import com.briup.cms.exception.ServiceException;
import com.briup.cms.result.ResultCode;
import com.briup.cms.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public  boolean preHandle(@NonNull HttpServletRequest request,
                              @NonNull HttpServletResponse response,
                              @NonNull Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        // 从 HTTP请求头中取出 token
        String token = request.getHeader("Authorization");
        if (token == null) {
            log.error("无token，请重新登录");
            throw new ServiceException(ResultCode.TOKEN_NOT_EXIST);
        }
        // 验证 token
        try {
            //解析JWT
            Claims claims = JwtUtil.parseJWT(token);
            String id = String.valueOf(claims.get("userId"));
            //专门为 /auth/user/info 提供服务
            request.setAttribute("userId",id);
        }catch (ExpiredJwtException e){
            //登录到期
            log.error("登录到期");
            throw new ServiceException(ResultCode.TOKEN_TIMEOUT);
        }catch (MalformedJwtException e){
            //令牌失效
            log.error("令牌失效");
            throw new ServiceException(ResultCode.TOKEN_VALIDATE_ERROR);
        }catch (Exception e){
            log.error(e.getMessage());
            //服务器内部错误
            throw new ServiceException(ResultCode.PROGRAM_INTERNAL_ERROR);
        }
        return true;
    }
}